from django.shortcuts import render
from django.views.generic import View
# Create your views here.
from django.http import JsonResponse, HttpResponse
from user_info.models import *
import random
from product.views import *


def make_code(size=6):
    res = ''
    for i in range(size):
        s1 = str(random.randint(0, 9))
        s2 = chr(random.randint(65, 90))
        res += random.choice([s1, s2])
    return res


class Login(View):
    def get(self, request, *args, **kwargs):
        name = self.request.GET.get('name')
        # 制作验证码
        code = make_code()
        password = self.request.GET.get('password')
        try:
            user = User.objects.get(name=name)
            if user and user.password == password:
                # 清除用户之前的session信息
                try:
                    del self.request.session[name]
                    print('清除了之前登录的session')
                except Exception:
                    pass
                finally:
                    #  设置新的session信息
                    self.request.session[name] = code
                    return JsonResponse({"status_num": 0, 'massage': 'password correct!', 'code': code})
            else:
                return JsonResponse({'status_num': 1, 'massage': 'password wrong or user not exist!'})

        except Exception as e:
            return JsonResponse({'status_num': 1, 'massage': 'not found user massage!'})

    # post请求删除用户session信息
    def post(self, request, *args, **kwargs):
        self.request.session.clear()
        return HttpResponse('delete successful!')
